package com.rc.saas.tenant.controller.system;

import com.rc.saas.tenant.common.vo.TResponse;
import com.rc.saas.tenant.component.UploadComponent;
import com.rc.saas.tenant.model.system.RcCustomerService;
import com.rc.saas.tenant.model.tenant.Tenant;
import com.rc.saas.tenant.model.tenant.TenantUser;
import com.rc.saas.tenant.service.system.RcCustomerSerService;
import com.rc.saas.tenant.service.tenant.TenantService;
import com.rc.saas.tenant.shiro.ShiroUtils;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;

import java.util.Date;

@Controller
@RequestMapping("/sys/customerService")
public class RcCustomerServiceController {

    private static Logger logger = LogManager.getLogger(RcCustomerServiceController.class);
    @Autowired
    private RcCustomerSerService customerSerService;

    @Autowired
    private TenantService tenantService;

    @Autowired
    private UploadComponent uploadComponent;

    @RequestMapping("/index")
    public String index(Model model) {
        RcCustomerService info = customerSerService.selectByPrimaryKey(1l);
        model.addAttribute("info", info);
        return "/templates/system/customerService";
    }

    @ResponseBody
    @RequestMapping("/saveCustomerService")
    public TResponse saveCustomerService(RcCustomerService info,
                @RequestParam(value = "file1", required = false) MultipartFile file1) {
        TenantUser user = ShiroUtils.getSessionUser();
        Tenant tenant = tenantService.selectByPrimaryKey("MA4T4JPE8");

        info.setLastUpdatedBy(user.getLoginName());
        info.setLastUpdatedTime(new Date());
        try {
            if (file1 != null && file1.getSize() != 0 && file1.getContentType().contains("image")) {
                String imgUrl = uploadComponent.uploadFile(user.getTenantCode(), file1);
                info.setQrcodeImg(imgUrl);
                if (tenant != null) {
                    tenant.setServiceImg(imgUrl);
                }
            }
            tenant.setServicePhone(info.getServiceIphone());
            tenantService.updateByPrimaryKeySelective(tenant);
            customerSerService.updateByPrimaryKey(info);
        }catch (Exception e){
            logger.error("保存失败", e);
            return TResponse.FAIL("保存失败");
        }
        return TResponse.SUCCESS();
    }
}
